#include "Locker.h"

Sem::Sem()
{
    if(sem_init(&sem_, 0, 0) != 0) {
        throw std::exception();
    }
}

Sem::Sem(int num)
{
    // initial resource = num
    if(sem_init(&sem_, 0, num) != 0) {
        throw std::exception();
    }
}

Sem::~Sem()
{
    sem_destroy(&sem_);
}

bool Sem::wait()
{
    return sem_wait(&sem_) == 0;
}

bool Sem::post()
{
    return sem_post(&sem_) == 0;;
}

Locker::Locker()
{
    if(pthread_mutex_init(&mutex_, NULL) != 0) {
        throw std::exception();
    }
}

Locker::~Locker()
{
    pthread_mutex_destroy(&mutex_);
}

bool Locker::lock()
{
    return pthread_mutex_lock(&mutex_) == 0;
}

bool Locker::unlock()
{
    return pthread_mutex_unlock(&mutex_) == 0;
}

pthread_mutex_t *Locker::get()
{
    return &mutex_;
}

Cond::Cond()
{
    if(pthread_cond_init(&cond_, NULL) != 0) {
        throw std::exception();
    }
}

Cond::~Cond()
{
    pthread_cond_destroy(&cond_);
}

bool Cond::wait(pthread_mutex_t *mutex)
{
    int ret = 0;
    ret = pthread_cond_wait(&cond_, mutex);
    return ret == 0;
}

bool Cond::timewait(pthread_mutex_t *mutex, struct timespec t)
{
    int ret = 0;
    ret = pthread_cond_timedwait(&cond_, mutex, &t);
    return ret == 0;
}

bool Cond::signal()
{
    return pthread_cond_signal(&cond_) == 0;
}

bool Cond::broadcast()
{
    return pthread_cond_broadcast(&cond_) == 0;
}
